package cn.lingyangwl.agile.system.listener;

import cn.lingyangwl.agile.system.model.mq.ResourceSyncMQ;
import cn.lingyangwl.agile.system.model.entity.RamModule;
import cn.lingyangwl.agile.system.service.RamModuleService;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = ResourceSyncMQ.QUERY_NOTICE_INIT, durable = "true"), key = ResourceSyncMQ.KEY_NOTICE_INIT,
                exchange = @Exchange(value = ResourceSyncMQ.EXCHANGE_INIT))
})
public class ResourceSyncInitListener {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RamModuleService moduleService;

    @RabbitHandler
    public void onMessage(String data, Channel channel, Message message) throws Exception {
        try {
            List<RamModule> list = moduleService.list();
            rabbitTemplate.convertAndSend(ResourceSyncMQ.EXCHANGE_REFRESH, ResourceSyncMQ.KEY_NOTICE_REFRESH , new ResourceSyncMQ(list).toMessage());
            log.info("消费成功: {}", data);
        } catch (Exception e) {
            log.error("消费失败: {}, msg: {}", e.getMessage(), data);
            if (e instanceof NullPointerException) {
                e.printStackTrace();
            } else if (e instanceof BizException) {
                throw e;
            }
            throw new BizException(-1, "mq消费错误");
        }
    }
}
